function varargout = TLDataStoreWriteDlg(action,varargin)

% TL_DATASTOREWRITE_DLG manages the user interface for TargetLink Datastore Write block
%
% SYNTAX dlgInfo = TLDatastorewriteDlg('GetDlgInfo');
%   gets dialog info of TargetLink Datastore Write block
%
%   INPUT ARGUMENTS
%   -/-      
%
%   OUTPUT ARGUMENTS
%   dlgInfo     dialog information contains pageNames etc.
%
% SYNTAX [sheetDims, ctrlPos] = TLDatastorewriteDlg('CtrlPositions', pageName, commonGeom, dlgInfo, sheetDims);
%   calculates the control positions of all controls of dialog page: <pageName>
%
%   INPUT ARGUMENTS
%   pageName        name of current page
%   commonGeom      common geometry data
%   dlgInfo         dialog information contains pageNames etc.
%   sheetDims       dimension of sheet
%
%   OUTPUT ARGUMENTS
%   sheetDims       modified dimension of sheet
%   ctrlPos         positions of controls
%
% SYNTAX dlgdata = TLDatastorewriteDlg('Create', pageName, dlgfig, dlgdata);
%   creates all controls of dialog page: <pageName>
%
%   INPUT ARGUMENTS
%   pageName        name of current page
%   dlgfig          figure handle
%   dlgdata         dialog data
%
%   OUTPUT ARGUMENTS
%   dlgdata         modified dialog data
%
% SYNTAX [dlgdata,bModified] = TLDatastorewriteDlg('Manage', pageName, dlgfig, dlgdata, pageAction);
%   manages all actions of dialog page: <pageName>
%
%   INPUT ARGUMENTS
%   pageName        name of current page
%   dlgfig          figure handle
%   dlgdata         dialog data
%   pageAction      modified control of current page
%
%   OUTPUT ARGUMENTS
%   dlgdata         modified dialog data
%   bModified       flag = 1, if dialog data are modified, =0 otherwise
%
% SYNTAX dlgdata = TLDatastorewriteDlg('Update', dlgfig, dlgdata, pageNum);
%   updates all controls of dialog page: <pageNum>
%
%   INPUT ARGUMENTS
%   dlgfig          figure handle
%   dlgdata         dialog data
%   pageNum         number of current page
%
%   OUTPUT ARGUMENTS
%   dlgdata         modified dialog data
%
% SYNTAX TLDatastorewriteDlg('Apply', dlgfig, dlgdata);
%   writes current blockdata to block and DD
%
%   INPUT ARGUMENTS
%   dlgfig      handle for dialog figure
%   dlgdata     dialog data
%
%   OUTPUT ARGUMENTS
%   - / -


% Author(s): D. Andoleit, T. Pietzsch
% $RCSfile: TLDatastorewriteDlg.m $
% $ProjectName: e:/ARC/Components/HostSW/SimulinkBlocksets/TLBlocksets/CommonBlockset/CommonBlockset_SimBlocksUI/Sources/MSrc/project.pj $
% $Revision: 1.11 $
% $Date: 2011/03/17 11:52:28MEZ $
%
% Copyright ?2011 dSPACE GmbH. All rights reserved.


switch action

    case 'GetDlgInfo'
        hBlock = varargin{1};
        dlgInfo = tl_get_dlginfodefaults('tlsim');
        titleName = 'Data Store Write';
        pathinfo = tl_pathinfo(hBlock);
        dlgInfo.title = sprintf('TargetLink %s: %s', titleName, pathinfo.shortDisplayName);
        dlgInfo.pageNames   = {'Variable', 'Documentation'};
        varargout{1} = dlgInfo;
        varargout{2} = get_tlcg_data(hBlock);

    case 'CtrlPositions'
        pageName     = varargin{1};
        commonGeom   = varargin{2};
        %dlgInfo      = varargin{3};
        sheetDims    = varargin{4};
        switch pageName
            case 'Variable'
                [sheetDims,ctrlPos] = FcnVariableCtrlPositions(commonGeom);
                
            case 'Documentation'
                bTblBlock = 0;
                bCodeComment = 0;
                [sheetDims,ctrlPos] = ...
                    TLManageDocCtrls('ctrlpos',commonGeom,sheetDims,bCodeComment,bTblBlock);
        end
        varargout{1} = sheetDims;
        varargout{2} = ctrlPos;

    case 'Create'
        pageName = varargin{1};
        dlgfig   = varargin{2};
        dlgdata  = varargin{3};
        pageNum  = strmatch(pageName, dlgdata.pageNames, 'exact');
        switch pageName
            case 'Variable'
                dlgdata = ...
                    FcnCreateVariablePage(pageNum, dlgfig, dlgdata);
                
            case 'Documentation'
                dlgdata = ...
                    TLManageDocCtrls('create', pageNum, dlgfig, dlgdata);
        end
        dlgdata.pageData{pageNum}.ctrlPos = [];
        varargout{1} = dlgdata;

    case 'Manage',
        pageName   = varargin{1};
        dlgfig     = varargin{2};
        dlgdata    = varargin{3};
        pageAction = varargin{4};
        pageNum    = strmatch(pageName,dlgdata.pageNames,'exact');

        switch pageName
            case 'Variable'
                [dlgdata,bModified] = ...
                    FcnManageVariablePage(pageNum,dlgdata,pageAction);
                
            case 'Documentation'
                [dlgdata,bModified] = ...
                    TLManageDocCtrls('callback',pageNum,dlgfig,dlgdata,pageAction);
        end
        varargout{1} = dlgdata;
        varargout{2} = bModified;

    case 'ManageSystemIcons',
        dlgfig     = varargin{1};
        dlgdata    = varargin{2};
        pageAction = varargin{3};
        [dlgdata, bModified] = FcnManageSystemIcons(dlgfig,dlgdata,pageAction);
        varargout{1} = dlgdata;
        varargout{2} = bModified;

    case 'Update'
        dlgfig  = varargin{1};
        dlgdata = varargin{2};
        pageNum = varargin{3};

        if pageNum == 1
            % Variable page
            dlgdata = FcnUpdateVariablePage(dlgdata, dlgfig);
        elseif pageNum == 2
            % documentation page
            TLManageDocCtrls('update', pageNum, dlgfig, dlgdata);
        end
        varargout{1} = dlgdata;

    case 'Apply'
        dlgdata  = varargin{2};
        bClose   = varargin{3};
        [dlgdata, bClose] = tl_apply_blockdata(dlgdata, bClose);
        varargout{1} = dlgdata;
        varargout{2} = bClose;

    otherwise
        error(['Invalid action "' action '"']);

end


%-----------------------------------------------------------------------------------------
% FcnManageSystemIcons manage actions of toolbar icons
%
% INPUT ARGUMENTS
%   dlgfig      handle for dialog figure
%   dlgdata     dialog data
%   action      action at one control of current page
%
% OUTPUT ARGUMENTS
%   dlgdata     modified dialog data
%   bModified   flag = 1, if dialog data are modified, =0 otherwise
%-----------------------------------------------------------------------------------------
function [dlgdata, bModified] = FcnManageSystemIcons(dlgfig, dlgdata, action) %#ok

bModified = false;
switch action
    case 'EditCode'
        % look for associated production code file
        [codefile,blockstr] = get_codefile(dlgdata.model);
        if ~isempty(codefile)
            codeedit(codefile,blockstr);
        end

    case 'ViewCode'
        tl_create_links_to_model('ShowComputation',dlgdata.model, 'output');

    otherwise
        error('Invalid callback');

end % switch(action)


%-----------------------------------------------------------------------------------------
% FcnVariableCtrlPositions calculates positions for all controls on variable page
%
% INPUT ARGUMENTS
%   commonGeom      common geometrie information
%
% OUTPUT ARGUMENTS
%   sheetDims       modified dimension of sheet
%   ctrlPos         positions of controls
%
% HINT:
% Positions are calculated from the bottom left of the figure to avoid
% dependencies on figure size
%-----------------------------------------------------------------------------------------
function [sheetDims, ctrlPos] = FcnVariableCtrlPositions(commonGeom)

% variable name, stepsize controls
strings_and_styles = {...
    'Data store name:',     'text';
    repmat('m',1,18),       'edit';
    'Sample time:',         'text'};

[nameLabelSize, ...
    genericEditSize, ...
    stepsizeLabelSize] = ...
    ds_get_uicontrol_sizes(commonGeom,strings_and_styles);

widths = ...
    [nameLabelSize(1)
    genericEditSize(1)
    stepsizeLabelSize(1)
    genericEditSize(1)];
[col,colWidth,colDelta] = ds_get_gui_columns(widths,commonGeom);

% variable groupbox
cx = commonGeom.figSideEdgeBuffer + commonGeom.sheetSideEdgeBuffer;
cy = commonGeom.bottomSheetOffset + ...
    commonGeom.sheetBottomEdgeBuffer;
varGroupboxWidth = ...
    sum(colWidth) + colDelta + ...
    2*commonGeom.frameSideEdgeBuffer;
varGroupboxHeight = ...
    commonGeom.editHeight + ...
    commonGeom.frameTopEdgeBuffer + ...
    commonGeom.frameBottomEdgeBuffer;

ctrlPos.varGroupbox = ...
    [cx cy varGroupboxWidth varGroupboxHeight];

% variable name controls
cx = col(1);
cy = commonGeom.frameBottomEdgeBuffer;
ctrlPos.nameLabel = ...
    [cx cy nameLabelSize];
cx = col(2);
ctrlPos.nameEdit = ...
    [cx cy genericEditSize];
cx = col(3);
ctrlPos.stepsizeLabel = ...
    [cx cy stepsizeLabelSize];
cx = col(4);
ctrlPos.stepsizeEdit = ...
    [cx cy genericEditSize];

width = varGroupboxWidth + ...
    2*commonGeom.frameSideEdgeBuffer;
height = ...
    commonGeom.sheetTopEdgeBuffer + ...
    varGroupboxHeight + ...
    commonGeom.sheetBottomEdgeBuffer;

sheetDims = [width height];


%-----------------------------------------------------------------------------------------
% FcnCreateVariablePage creates the figure window
%
% INPUT ARGUMENTS
%   pageNum     number of current page
%   dlgfig      handle for dialog figure
%   dlgdata     dialog data
%
% OUTPUT ARGUMENTS
%   dlgdata     modified dialog data
%-----------------------------------------------------------------------------------------
function dlgdata = FcnCreateVariablePage(pageNum,dlgfig,dlgdata)

ctrlPos = dlgdata.pageData{pageNum}.ctrlPos;
data = dlgdata.data;
pageName = dlgdata.pageNames{pageNum};
% variable group box
Children.varGroupbox = uipanel( ...
    'Parent',            dlgfig, ...
    'Title',            {'Data store name and sample time'}, ...
    'Units',            'pixels', ...
    'Position',          ctrlPos.varGroupbox);

% stepsize controls
Children.stepsizeLabel = uicontrol( ...
    'Parent',             Children.varGroupbox, ...
    'Style',              'text', ...
    'String',             'Sample time:', ...
    'Position',           ctrlPos.stepsizeLabel);

Children.stepsizeEdit = uicontrol( ...
    'Parent',             Children.varGroupbox, ...
    'BackgroundColor',    'w', ...
    'Style',              'edit', ...
    'String',             data.dt, ...
    'Position',           ctrlPos.stepsizeEdit, ...
    'Callback',           sprintf('tldlg(''%s'',gcbf,''stepsizeEdit'')',pageName));


Children.nameLabel = uicontrol( ...
    'Parent',             Children.varGroupbox, ...
    'Style',              'text', ...
    'String',             'Data store name:', ...
    'Position',           ctrlPos.nameLabel);

Children.nameEdit = uicontrol( ...
    'Parent',             Children.varGroupbox, ...
    'BackgroundColor',    'w', ...
    'Style',              'edit', ...
    'String',             data.datastorename, ...
    'Position',           ctrlPos.nameEdit, ...
    'Callback',           sprintf('tldlg(''%s'',gcbf,''nameEdit'')',pageName));

dlgdata.pageData{pageNum}.children = Children;


%-----------------------------------------------------------------------------------------
% FcnManageVariablePage manages control actions of variable page
%
% INPUT ARGUMENTS
%   pageNum     number of current page
%   dlgdata     dialog data
%   pageAction  action at one control of current page
%
% OUTPUT ARGUMENTS
%   dlgdata     modified dialog data
%   bModified   flag = 1, if dialog data are modified, =0 otherwise
%-----------------------------------------------------------------------------------------
function [dlgdata, bModified] = FcnManageVariablePage(pageNum, dlgdata, pageAction)

Children = dlgdata.pageData{pageNum}.children;

switch pageAction
    case 'nameEdit'
        varstr = tl_deblank(get(Children.nameEdit, 'String'), 2);
        bMatch = (length(varstr) <= 31) && ...
            ds_regexp('[a-zA-Z]+[_a-zA-Z0-9]*', varstr);
        if ~bMatch
            beep;
        else
            dlgdata.data.datastorename = varstr;
        end
        bModified = true;

    case 'stepsizeEdit'
        dtStr = tl_deblank(get(Children.stepsizeEdit, 'String'), 2);
        if ~isempty(dtStr)
            dlgdata.data.dt = get(Children.stepsizeEdit, 'String');
        else
            beep;
        end
        bModified = true;

    otherwise
        error(['Invalid Action "' pageAction '"'])

end


%--------------------------------------------------------------------------
% FcnUpdateVariablePage updates the controls of the variable tab
%
% INPUT ARGUMENTS
%   dlgdata     dialog data
%   dlgfig      figure handle of dialog
%
% OUTPUT ARGUMENTS
%   dlgdata     modified dialog data
%--------------------------------------------------------------------------
function dlgdata = FcnUpdateVariablePage(dlgdata, dlgfig)

Children = dlgdata.pageData{1}.children;

nameEditCtrlStatus = struct('enable', 'on');
stepsizeEditCtrlStatus = struct('enable', 'on');

nameEditCtrlStatus.string = dlgdata.data.datastorename;
stepsizeEditCtrlStatus.string = dlgdata.data.dt;

ctrlsList = {'nameEdit', 'stepsizeEdit'};
for ctrlsNo=1:length(ctrlsList)
    ctrl = eval(['Children.', ctrlsList{ctrlsNo}]);
    UserData = get(ctrl, 'UserData');
    UserData.ctrlStatus = eval([ctrlsList{ctrlsNo} 'CtrlStatus']);
    set(ctrl, 'UserData', UserData);
end
TLSetCtrlsStatus(dlgfig,Children, ctrlsList);
